package com.finalministry.db.factory;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import com.finalministry.db.dao.impl.AddressDAO;
import com.finalministry.db.dao.impl.CountryDAO;

/**
 * Singleton Database Factory used by the DAOs
 * 
 * @author lussopi
 */
public class DatabaseFactory {

	private static String persistenceUnitName = "UnitTests";

	private static EntityManagerFactory factory = null;

	private static Long congregationID = null;

	public static synchronized EntityManagerFactory getInstance() {

		if (factory == null) {

			factory = Persistence.createEntityManagerFactory(persistenceUnitName);

			if (factory == null) {
				System.err.println("No persistence.xml found, I will exit the application!");
				System.exit(0);
			}
		} else {
			System.err.println("EntityManagerFactory already created.");
		}

		return factory;
	}

	public static String getPersistenceUnitName() {

		return persistenceUnitName;
	}

	/**
	 * TODO: call this setter from inside a Initial Class during application
	 * setup
	 * 
	 * @param persistenceUnitName
	 */
	public static void setPersistenceUnitName(String persistenceUnitName) {

		DatabaseFactory.persistenceUnitName = persistenceUnitName;
	}

	public static CountryDAO getCountryDAO() {
		return new CountryDAO();
	}

	public static AddressDAO getAddressDAO() {
		return new AddressDAO();
	}

	public static void setCongregationID(Long congregationID) {
		DatabaseFactory.congregationID = congregationID;
	}

	public static Long getCongregationID() {
		return congregationID;
	}

}
